package org.jeecgframework.web.controller;
import com.mybatis.ext.WiseCoreService;

import org.jeecgframework.web.system.pojo.base.CbsDeliverErrorLogEntity;
import org.jeecgframework.web.service.CbsDeliverErrorLogServiceI;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import java.io.OutputStream;

import org.jeecgframework.core.util.BrowserUtils;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jeecgframework.core.util.ResourceUtil;

import java.io.IOException;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.util.Map;

import org.jeecgframework.core.util.ExceptionUtil;



/**   
 * @Title: Controller
 * @Description: 发货单异常记录表
 * @author onlineGenerator
 * @date 2018-03-01 10:31:11
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsDeliverErrorLogController")
public class CbsDeliverErrorLogController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CbsDeliverErrorLogController.class);

	@Autowired
	private CbsDeliverErrorLogServiceI cbsDeliverErrorLogService;
	@Autowired
	private SystemService systemService;
	private String message;

	@Autowired
	private WiseCoreService wiseCoreService;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 发货单异常记录表列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "cbsDeliverErrorLog")
	public ModelAndView cbsDeliverErrorLog(HttpServletRequest request) {
		System.out.println("执行了...");
		return new ModelAndView("com/zybk/cbs_deliver_error_log/cbsDeliverErrorLogList");

	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(CbsDeliverErrorLogEntity cbsDeliverErrorLog,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		Map param = new HashMap<>();
        boolean flag = false; //页面查询条件为空时不做查询
		Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()) {
            if (key.equals("code") || key.equals("isClose") || key.equals("needSystemRevise") ||
                    key.equals("createDate_begin") || key.equals("createDate_end")) {
                if (!StringUtil.isEmpty(parameterMap.get(key)[0])) {
                    flag = true;//页面 查询条件为空不做查询
                    break;
                }
            }
        }
       if (flag) {
			for (Object key : request.getParameterMap().keySet()) {
				if ((String[]) request.getParameterMap().get(key) != null) {
					for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
						if (((String[]) request.getParameterMap().get(key))[i] != null) {
							param.put(key, ((String[]) request.getParameterMap().get(key))[i]);
						}
					}
				}
			}
        } else {
        	param.put("isClose", 1);
        }
		wiseCoreService.selectDataGrid("selectDeliverErrorDatagrid", param, dataGrid);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 发货单异常记录表新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(CbsDeliverErrorLogEntity cbsDeliverErrorLog, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(cbsDeliverErrorLog.getId())) {
			cbsDeliverErrorLog = cbsDeliverErrorLogService.getEntity(CbsDeliverErrorLogEntity.class, cbsDeliverErrorLog.getId());
			req.setAttribute("cbsDeliverErrorLogPage", cbsDeliverErrorLog);
		}
		return new ModelAndView("com/zybk/cbs_deliver_error_log/cbsDeliverErrorLog-add");
	}
	

	/**
	 * 添加发货单异常记录表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(CbsDeliverErrorLogEntity cbsDeliverErrorLog, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "发货单异常记录表添加成功";
		try{
			cbsDeliverErrorLogService.save(cbsDeliverErrorLog);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "发货单异常记录表添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 发货单异常记录表编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(CbsDeliverErrorLogEntity cbsDeliverErrorLog, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(cbsDeliverErrorLog.getId())) {
			cbsDeliverErrorLog = cbsDeliverErrorLogService.getEntity(CbsDeliverErrorLogEntity.class, cbsDeliverErrorLog.getId());
			req.setAttribute("cbsDeliverErrorLogPage", cbsDeliverErrorLog);
		}

		boolean flag = false;
		TSUser user = ResourceUtil.getSessionUserName();
		List<Map<String, Object>> roleList = systemService.findForJdbc("SELECT * FROM t_s_role r LEFT JOIN t_s_role_user u ON r.id = u.roleid where u.userid = '" + user.getId() + "';");
		if (StringUtil.isNotEmpty(roleList)) {
			if (roleList.size() > 0) {
				String num = (String) roleList.get(0).get("rolecode");
				if (num.equals(StaticValue.ROLE_CODE_ADMIN)) {
					flag = true;
				}
			}
		}

		if (flag) {
			return new ModelAndView("com/zybk/cbs_deliver_error_log/cbsDeliverErrorLog-adminUpdate");
		} else {
			return new ModelAndView("com/zybk/cbs_deliver_error_log/cbsDeliverErrorLog-update");
		}
	}
	
	/**
	 * 更新发货单异常记录表
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(CbsDeliverErrorLogEntity cbsDeliverErrorLog, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		Date date=new Date();
		String HandleDescription=request.getParameter("HandleDescription");
		String handleResult=request.getParameter("handleResult");
		//获取登录用户
		TSUser user = ResourceUtil.getSessionUserName();
		message = "发货单异常处理成功";
		CbsDeliverErrorLogEntity t = cbsDeliverErrorLogService.get(CbsDeliverErrorLogEntity.class, cbsDeliverErrorLog.getId());
		try {
			boolean flag = false;
			List<Map<String, Object>> roleList = systemService.findForJdbc("SELECT * FROM t_s_role r LEFT JOIN t_s_role_user u ON r.id = u.roleid where u.userid = '" + user.getId() + "';");
			if (StringUtil.isNotEmpty(roleList)) {
				if (roleList.size() > 0) {
					String num = (String) roleList.get(0).get("rolecode");
					if (num.equals(StaticValue.ROLE_CODE_ADMIN)) {
						flag = true;
					}
				}
			}

			if (flag) {
				t.setAdminAbnormalResult(cbsDeliverErrorLog.getAdminAbnormalResult());
				t.setAdminDescription(cbsDeliverErrorLog.getAdminDescription());
				t.setAdminUpdateDate(new Date());
				t.setAdminUpdateBy(user.getRealName());
				t.setNeedSystemRevise("1");
			}else{
				t.setHandleDescription(HandleDescription);
				t.setHandleResult(handleResult);
				t.setHandleDate(date);
				t.setHandleUser(user.getUserName());
				t.setNeedSystemRevise("2");
			}
			t.setIsClose(2);
			cbsDeliverErrorLogService.saveOrUpdate(t);
			if (flag) {
                systemService.updateBySqlString("update CBS_DELIVER_ERROR_LOG set update_name='"+""+"',update_date=null where id = '"+cbsDeliverErrorLog.getId()+"'");
            }
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "发货单异常处理失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}



	
	/**
	 * 删除发货单异常记录表
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(CbsDeliverErrorLogEntity cbsDeliverErrorLog, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		cbsDeliverErrorLog = systemService.getEntity(CbsDeliverErrorLogEntity.class, cbsDeliverErrorLog.getId());
		message = "发货单异常记录表删除成功";
		try{
			cbsDeliverErrorLogService.delete(cbsDeliverErrorLog);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "发货单异常记录表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除发货单异常记录表
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		message = "发货单异常记录表删除成功";
		try{
			for(String id:ids.split(",")){
				CbsDeliverErrorLogEntity cbsDeliverErrorLog = systemService.getEntity(CbsDeliverErrorLogEntity.class, 
				id
				);
				cbsDeliverErrorLogService.delete(cbsDeliverErrorLog);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "发货单异常记录表删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		return new ModelAndView("com/zybk/cbs_deliver_error_log/cbsDeliverErrorLogUpload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(CbsDeliverErrorLogEntity cbsDeliverErrorLog,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		TSUser user = ResourceUtil.getSessionUserName();
		CriteriaQuery cq = new CriteriaQuery(CbsDeliverErrorLogEntity.class, dataGrid);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsDeliverErrorLog, request.getParameterMap());
		List<CbsDeliverErrorLogEntity> cbsDeliverErrorLogs = this.cbsDeliverErrorLogService.getListByCriteriaQuery(cq,false);
		for (int i =0;i<cbsDeliverErrorLogs.size();i++){
			if (cbsDeliverErrorLogs.get(i).getIsClose()!=null){
				if (cbsDeliverErrorLogs.get(i).getIsClose()==1){
					cbsDeliverErrorLogs.get(i).setCloseDes("开启");
				}
				if (cbsDeliverErrorLogs.get(i).getIsClose()==2){
					cbsDeliverErrorLogs.get(i).setCloseDes("关闭");
				}
				if("1".equals(cbsDeliverErrorLogs.get(i).getNeedSystemRevise())){
					cbsDeliverErrorLogs.get(i).setNeedSystemReviseDesc("是");
				}
				if("2".equals(cbsDeliverErrorLogs.get(i).getNeedSystemRevise())){
					cbsDeliverErrorLogs.get(i).setNeedSystemReviseDesc("否");
				}
				if (cbsDeliverErrorLogs.get(i).getCbsDeliverId()!=null){
					cbsDeliverErrorLogs.get(i).setCode(cbsDeliverErrorLogs.get(i).getCbsDeliverId().getCode());
				}
			}
		}
		modelMap.put(NormalExcelConstants.FILE_NAME,"发货单异常记录表");
		modelMap.put(NormalExcelConstants.CLASS,CbsDeliverErrorLogEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("发货单异常记录表列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,cbsDeliverErrorLogs);
		systemService.addLog(user.getRealName()+"导出"+cbsDeliverErrorLogs.size()+"条发货单异常记录记录", Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(CbsDeliverErrorLogEntity cbsDeliverErrorLog,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		modelMap.put(TemplateExcelConstants.FILE_NAME, "发货单异常记录表");
		modelMap.put(TemplateExcelConstants.PARAMS,new TemplateExportParams("Excel模板地址"));
		modelMap.put(TemplateExcelConstants.MAP_DATA,null);
		modelMap.put(TemplateExcelConstants.CLASS,CbsDeliverErrorLogEntity.class);
		modelMap.put(TemplateExcelConstants.LIST_DATA,null);
		return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<CbsDeliverErrorLogEntity> listCbsDeliverErrorLogEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(),CbsDeliverErrorLogEntity.class,params);
				for (CbsDeliverErrorLogEntity cbsDeliverErrorLog : listCbsDeliverErrorLogEntitys) {
					cbsDeliverErrorLogService.save(cbsDeliverErrorLog);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
}
